const svgCaptcha = require('svg-captcha');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const UserModel = require('../db/models/user');
const MenuModel = require('../db/models/menu');

// 获取验证码
const getCaptchaImage = async function (ctx, next) {
  // 生成加法形式的验证码
  const captcha = svgCaptcha.createMathExpr({
    fontSize: 50,
    width: 120,
    height: 34,
    background: '#efefef',
  });

  // 生成验证码
  // const captcha = svgCaptcha.create({
  //   size: 4,
  //   fontSize: 50,
  //   width: 120,
  //   height: 36,
  //   background: '#efefef',
  // });

  // 设置响应头
  ctx.response.type = 'image/svg+xml';

  ctx.body = captcha;
};
/* jsonwebtoken */
// let token = ctx.header.authorization.split(' ')[1];
// jwt.verify(token, 'mb-token', (err, paylod) => {});
/* koa-jwt */
// let paylod = ctx.state.user;

// 登录验证
const login = async function (ctx, next) {
  let data = ctx.request.body;
  let target = await UserModel.find({ username: data.username });
  let status;
  if (target.length === 0) {
    status = {
      msg: '用户名不存在！',
      success: false,
    };
  } else {
    if (!bcrypt.compareSync(data.password, target[0].password)) {
      status = {
        msg: '用户名与密码不匹配！',
        success: false,
      };
    } else {
      const secret = 'mb-token';
      const token = jwt.sign(
        {
          username: target[0].username,
          _id: target[0]._id,
        },
        secret,
        //{ expiresIn: '1h' }
        { expiresIn: 60 * 60 * 24 }
      );
      status = {
        success: true,
        token,
      };
    }
  }
  ctx.body = status;
};

// 获取用户信息
const getUserInfo = async function (ctx, next) {
  const paylod = ctx.state.user;
  let userInfo = await UserModel.find({ _id: paylod._id });
  ctx.body = userInfo;
};

// 获取导航路由
const getRouters = async function (ctx, next) {
  const query = ctx.request.query;
  const roles = query.roles.split(',');
  let routers = await MenuModel.find({ role: { $in: roles } }).sort({ sort: 1 });
  for (let i = 0; i < routers.length; i++) {
    if (routers[i].parent) {
      let idx = routers.findIndex((r) => r.key === routers[i].parent);
      routers[idx].children.push(routers[i]);
    }
  }
  let tree = routers.filter((i) => !i.parent);
  // 排序
  ctx.body = {
    routers,
    tree,
  };
};

module.exports = {
  getCaptchaImage,
  login,
  getUserInfo,
  getRouters,
};
